/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.icee.myth.gm.controller;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import com.icee.myth.gm.GmServer;
import com.icee.myth.gm.channelhandler.HttpServerHandler;
import com.icee.myth.gm.client.GameServerClient;
import com.icee.myth.gm.player.SandBox;
import com.icee.myth.utils.Consts;

/**
 *
 * @author liuxianke
 */
public class ChangeSandboxController extends AbstractController {

    public ChangeSandboxController(int privilege) {
        super(privilege);
    }

    @Override
    public void process() {
        Long serverId = (Long) jobj.get("server");
        Long cid = (Long) jobj.get("cid");
        JSONObject sandboxObj = (JSONObject) jobj.get("sandbox");

        GameServerClient gameServerClient = null;
        if (serverId != null) {
            gameServerClient = GmServer.INSTANCE.getServer(serverId.intValue());
        }
        if (gameServerClient != null && cid != null && sandboxObj != null) {
            Long leader = (Long) sandboxObj.get("leader");
            Long helper = (Long) sandboxObj.get("helper");
            JSONArray slots = (JSONArray) sandboxObj.get("slots");
            if ((leader != null) && (helper != null) && (slots != null) && (slots.size() == SandBox.MAX_SLOT_NUM)) {
                int[] tmpArr = new int[SandBox.MAX_SLOT_NUM];
                for (int i = 0; i < SandBox.MAX_SLOT_NUM; i++) {
                    tmpArr[i] = (int) (long) (Long) slots.get(i);
                }
                SandBox sandBox = new SandBox(tmpArr, (int) (long) leader, (int) (long) helper);

                if (gameServerClient.changeSandbox((int)(long) cid, sandBox)) {
                    dbHandler.insertGmOperateLog(userData.userName, Consts.GMOPERATELOG_CHANGE_SANDBOX, jobj.toJSONString());
                    HttpServerHandler.writeResponse(request, e.getChannel(), "text/html; charset=UTF-8", "{\"result\":0}", null);
                } else {
                    HttpServerHandler.writeResponse(request, e.getChannel(), "text/html; charset=UTF-8", "{\"result\":-1,\"error\":\"change sandbox error\"}", null);
                }
            } else {
                HttpServerHandler.writeResponse(request, e.getChannel(), "text/html; charset=UTF-8", "{\"result\":-1,\"error\":\"sandbox param error\"}", null);
            }
        } else {
            HttpServerHandler.writeResponse(request, e.getChannel(), "text/html; charset=UTF-8", "{\"result\":-1,\"error\":\"param error\"}", null);
        }
    }
}
